<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:material:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="border-card">
      <el-tab-pane label="缩略图">
        <el-row class="lib-list" :gutter="20">
          <el-col :span="4" v-for="(item, index) in materialList" :key="index" >
            <el-card class="lib-card" :body-style="{ padding: '0px' }">
              <div class="img-div">
                <img :src="item.img" class="image">
              </div>
              <div style="padding: 14px;">
                <div class="name">{{item.name || ''}}</div>
                <div class="bottom clearfix">
                  <el-button type="text" class="button" @click="handleUpdate(item)" v-hasPermi="['cms:material:edit']">备注</el-button>
                  <el-button type="text" class="button" @click="handleDelete(item)" v-hasPermi="['cms:material:remove']">删除</el-button>
                  <el-button type="text" class="button showBtn" @click="copyLink" data-clipboard-action="copy"
                             :data-clipboard-text="item.img" >复制</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="列表">
        <el-table v-loading="loading" :data="materialList" >
          <el-table-column label="图片" align="center" prop="img" >
            <template slot-scope="scope">
              <el-image style="width: 100px" fit="contain" :src="scope.row.img"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="标题" align="center" prop="name" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="格式" align="center" prop="format" />
          <el-table-column label="大小" align="center" prop="fileSize" />
          <el-table-column label="上传时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['cms:material:edit']"
              >备注</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cms:material:remove']"
              >删除</el-button>
              <el-button type="text" class="button showBtn" @click="copyLink" data-clipboard-action="copy"
                         :data-clipboard-text="scope.row.img" >复制</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!--素材库列表-->


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改素材对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="550px" append-to-body>
      <div class="upload-container">
        <div id="el-upload-dragger">
          <el-upload
            :limit=maxFiles
            :action="url"
            :headers="headers"
            list-type="picture"
            :data="extraData"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb，数量不超过20个</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handClose">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="素材备注" :visible.sync="editopen" v-if="editopen" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="editopen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial,  delMaterial,getMaterial, updateMaterial } from "@/api/cms/material";
import {mapGetters} from "vuex";
import Clipboard from 'clipboard'
export default {
  name: "Material",
  props: {
    libraryId: {
      type: Number
    }
  },
  computed: {
    ...mapGetters(['token']),
    headers() {
      return{
        "Authorization": this.token // 直接从本地获取token就行
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 素材表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      editopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        libraryId: this.libraryId,
        name: null,
        img: null,
        isEnable: null,
        domain: null,
        prefix: null,
        format: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      url:process.env.VUE_APP_BASE_API + '/cms/material/upload',
      maxFiles: 20,
      extraData: {
        libraryId: this.libraryId
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询素材列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        libraryId: this.libraryId,
        name: null,
        img: null,
        isEnable: null,
        domain: null,
        prefix: null,
        format: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加素材";
    },
    /** 关闭按钮操作 */
    handClose() {
      this.open = false;
      this.getList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editopen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除素材编号为"' + ids + '"的数据项？').then(function() {
        return delMaterial(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterial(id).then(response => {
        this.form = response.data;
        this.imageUrl = response.data.libCover;
        this.editopen = true;
      });
    },

    copyLink () {
      let clipboard = new Clipboard('.showBtn')
      clipboard.on('success', e => {
        this.$message({ message: '复制成功', type: 'success' })
        clipboard.destroy() // 使用destroy可以清楚缓存
      })
      clipboard.on('error', e => {
        this.$message({ message: '复制失败', type: 'success' })
        clipboard.destroy()
      })
    }
  }
};
</script>
<style lang="less" scoped>
  .lib-list{
    .lib-card {
      align-items: center;
      margin-bottom: 20px;
      height: 270px;
      .name {
        width: 100%;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
      }
      .img-div{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        .image {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          margin: 0 auto;
          display: block;
          height: 200px;
        }
      }

    }
  }
  .upload-container {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: none;
    margin: 0 auto;
    width: 100%;
    #el-upload-dragger  {
      background-color: #fff;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      box-sizing: border-box;
      width: 100%;
      min-height: 180px;
      text-align: center;
      cursor: pointer;
      .el-icon-upload{
        font-size: 67px;
        color: #c0c4cc;
        margin: 40px 0 16px;
        line-height: 50px;
      }
      .el-upload__text {
        color: #606266;
        font-size: 14px;
        text-align: center;
        em {
          color: #409eff;
          font-style: normal;
        }
      }
    }
    .el-upload__tip {
      font-size: 12px;
      color: #606266;
      margin-top: 5px;
      text-align: left;
    }
  }
</style>
